﻿using System;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Microsoft.Extensions.Hosting;

namespace BlazorBoilerplate.Server
{
    public class Program
    {
        public static int Main(string[] args)
        {
            //获取环境变量及appsettings配置，为创建Logger实例作准备。
            //写法来自：https://github.com/serilog/serilog-settings-configuration
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{environment}.json", optional: true)
                .Build();

            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();

            try
            {
                //IdentityServer4 seed should be happening here but because of this bug https://github.com/aspnet/AspNetCore/issues/12349
                // 好像已解决
                //数据种子 the seeding is not implemented here.

                Console.WriteLine("正启动 HP Server ......");
                Console.WriteLine("=======================");

                Log.Information("Starting BlazorBoilerplate web server host");
                BuildHost(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("HP Server 出现启动问题，${ex}");

                Log.Fatal(ex, "BlazorBoilerplate Host terminated unexpectedly");
                return 1;
            }
        }

        public static IHostBuilder BuildHost(string[] args) =>
            //原克隆代码，没有升级 通用主机的写法。
            //Host.CreateDefaultBuilder(args)
            //.ConfigureAppConfiguration(config => .  )
            //.UseConfiguration(new ConfigurationBuilder()
            //    .AddCommandLine(args)
            //    .Build())
            //.UseStartup<Startup>()
            //.UseSerilog();


            //引入了Serilog 的三个包，Serilog.Settings.Configuration，提供 Serilog settings provider
            //读取 from Microsoft.Extensions.Configuration 源, 包括 .NET Core's appsettings.json 文件
            //参考 https://github.com/serilog/serilog-settings-configuration.

            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                              .UseSerilog();
                              
                             //或者使用下列配置,程序需要DI注入 ILoger 实例。
                             //.UseSerilog((ctx, config) => config.ReadFrom.Configuration(ctx.Configuration));
        });
    }
}
